from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 配置数据库
engine = create_engine('sqlite:///test.db', echo=True)
# 创建基类，用于定义模型
Base = declarative_base()

# 定义模型
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer,primary_key=True)
    name = Column(String)
    age = Column(Integer)

# 创建表
Base.metadata.create_all(engine)

# 创建会话
# 会话工厂
Session = sessionmaker(bind=engine)
# 会话
session = Session()

# 插入数据
new_user = User(name='Alice', age=25)
session.add(new_user)
session.commit()

# 查询数据
users = session.query(User).all()
for user in users:
    print(user.id,user.name,user.age)

# 关闭会话
session.close()
